const path = require('path')
const webpack = require('webpack')
const LodashModuleReplacementPlugin = require("lodash-webpack-plugin");
const glob = require('glob')

function resolve (dir) {
  return path.join(__dirname, dir)
}

const isProd = process.env.NODE_ENV === 'production'

//多入口配置
const pages = {}
const titles = {
  'index': '首页',
  'hkVideo': '海康播放器',
  'resource': '资源库管理',
  'deviceManage': '视频设备库',
  'warning': '预警管理 ',
  'sceneMonitor': '场景智能监控',
  'holographicData': '全息数据',
  'remote': '远程查床',
  'statics': '智能监控场景统计'
}
glob.sync('./src/pages/**/main.js').forEach(filePath => {
  let chunk = filePath.split('/')[filePath.split('/').length - 2]
  pages[chunk] = {
    entry: filePath,
    template: 'public/index.html',
    title: titles[chunk],
    filename: chunk + '.html',
    chunks: ['chunk-vendors', 'chunk-common', chunk]
  }
})

const vueConfig = {
  assetsDir: !isProd ? '' : 'static',
  // publicPath: !isProd ? '/' : './',
  productionSourceMap: false,
  lintOnSave: !isProd,
  // babel-loader no-ignore node_modules/*
  transpileDependencies: ['element-ui'],

  configureWebpack: {
    // webpack plugins
    plugins: [],
  },

  pages,

  chainWebpack: (config) => {
    config.resolve.alias
      .set('@', resolve('src'))
      .set('@assets', resolve('src/assets'))
      
    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule
      .oneOf('inline')
      .resourceQuery(/inline/)
      .use('vue-svg-icon-loader')
      .loader('vue-svg-icon-loader')
      .end()
      .end()
      .oneOf('external')
      .use('file-loader')
      .loader('file-loader')
      .options({
        name: 'assets/[name].[hash:8].[ext]'
      })

      // lodash按需加载
      config
      // .plugin("loadshReplace")
      // .use(new LodashModuleReplacementPlugin());
      
    // if prod is on
    if (isProd) {
        // ============压缩图片 start============
        // config.module
        //   .rule('images')
        //   .use('image-webpack-loader')
        //   .loader('image-webpack-loader')
        //   .options({ bypassOnDebug: true })
        //   .end()
        // ============压缩图片 end============

      // 删除预加载
      config.plugins.delete('preload');
      config.plugins.delete('prefetch');

      // 代码压缩
      // ..................
      // gzip压缩
      const productionGzipExtensions = ['html', 'js', 'css', 'json', 'ttf']
      config
        .plugin('compression')
        .use(require('compression-webpack-plugin'),[{
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: new RegExp(
            '\\.(' + productionGzipExtensions.join('|') + ')$'
          ),
          threshold: 10240, // 只有大小大于该值的资源会被处理 10240
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false // 删除原文件
        }])

      // 压缩代码
      config.optimization.minimize(true);
    }

  },

  devServer: {
    // historyApiFallback: true,
    port: 8989,
    disableHostCheck: true,
    host: 'local.oauth2.com',
    proxy: {
      '/ims/': {
        target: 'http://192.168.16.147:8989/', // 测试
        changeOrigin: true,
        // ws: false,
        // pathRewrite: { '^/medical-bs': '/bs'},
      }
    },
    historyApiFallback: {
      rewrites: [
        { from: /^\/$/, to: '/index.html' },
        { from: /^\/resource/, to: '/resource.html' },
        { from: /^\/remote/, to: '/remote.html' },
        { from: /^\/deviceManage/, to: '/deviceManage.html' },
        { from: /^\/sceneMonitor/, to: '/sceneMonitor.html' },
        { from: /^\/warning/, to: '/warning.html' }
      ]
    }
  },

  css: {
    // css预设器配置项
    loaderOptions: {
      // pass options to sass-loader
      scss: {
        // 引入全局变量样式,@使我们设置的别名,执行src目录
        // 注意：在 sass-loader v7 中，这个选项名是 "data"
        prependData: `@import "~@/config/config.scss"; `
      }
    },
  }

}

module.exports = vueConfig
